/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package spotkanie;

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author mateusz.ledzewicz
 */

public class CarThread extends Thread {
    private static double maxSpeed = 50;
    private double position;
    private double speed;
    private double acc = 0.005;
    private Long lastTime;
    private final CrossObject cross;
    boolean onCross = false;
    private PrintWriter out;
    
    public CarThread(double postion, CrossObject cross, PrintWriter out){
        this.cross = cross;
        this.position = postion;
        this.lastTime=System.nanoTime();
        this.out = out;
    }
    
    
    @Override
    public void run(){
        while(true){
            Double diff = (Double) ((System.nanoTime() - lastTime)/1000.0);
            speed += acc*diff;
            if(speed > maxSpeed) speed = maxSpeed;
            
            
            //Before cross
            
            if (!this.isOnCross(this.position) && this.isOnCross(this.position + speed *0.1)){
                Long beginTime = System.nanoTime();
                //this.log("Select In " + position);
                cross.select(this, CrossObject.in);
                //this.log("GO IN " + position);
                Long endTime = System.nanoTime();
                out.println(this.getName() + " " + (endTime-beginTime));
            }
            
            //Before drive out from cross
            if (this.isOnCross(this.position) && !this.isOnCross(this.position + speed *0.1)){
                //this.log("Select Out " + position);
                cross.select(this, CrossObject.out); 
                //this.log("GO OUT " + position);
            }
            
            this.move();   
            //this.log(position+"");
            
            //Fix position
            if(this.position >= 2100){
                this.position = 0;
            }
           
            this.lastTime = System.nanoTime();
        }
        
    }
    
    public void move(){
        this.position += speed *0.1;
        
    }

     public void log(String message){
         //if(this.getName().equalsIgnoreCase("Thread-7"))
            System.out.println(this.getName() + ";" + message );
    }
     
    public synchronized boolean isOnCross(double positionn){
        return ((positionn > 1000 && positionn < 1100) || (positionn > 2000 && positionn < 2100));
    }
    
    public synchronized boolean isOnCross(){
        return ((position > 1000 && position < 1100) || (position > 2000 && position < 2100));
    }
    
    
    public double getPosition(){
        return this.position;
    }
    public void setPosition(double value){
        this.position = value;
    }
    
    
    
}
